package com.baoteng.base.component;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.nfc.NfcAdapter;
import android.nfc.tech.NfcA;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.baoteng.base.R;
import com.baoteng.base.model.StateResource;
import com.baoteng.base.view.TopTitleBar;
import com.baoteng.component.other.NetworkUtils;
import com.baoteng.ui.progress.CustomProgressDialog;
import com.baoteng.ui.progress.ProgressSupport;
import com.baoteng.ui.progress.Progress;
import com.baoteng.ui.toast.BaseToast;

import java.util.List;

public abstract class BaseActivity extends FragmentActivity implements ProgressSupport {
    private static final String TAG = "BaseActivity";
    private ViewGroup rootLayout;
    private FrameLayout contentLayout;
    private CustomProgressDialog progressDialog;
    private Handler uiHandler;
    private TopTitleBar topTitleBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setLandscape();
        super.setContentView(R.layout.layout_activity);
        rootLayout = findViewById(R.id.activity_root_layout);
        contentLayout = findViewById(R.id.view_content);
        topTitleBar = findViewById(R.id.base_topbar);
        topTitleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        initTitle(topTitleBar);
    }

    public abstract void initTitle(TopTitleBar topTitleBar);

    public void setTitle(String title) {
        if (topTitleBar != null) {
            topTitleBar.setTitle(title);
        }
    }

    public void setRightTextVisible(boolean visible) {
        if (topTitleBar != null) {
            topTitleBar.setRightTextVisible(visible);
        }
    }

    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter tagDetected;

    public void initNfc(boolean showMsg) {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);//设备的NfcAdapter对象
        if (mNfcAdapter == null) {
            if (showMsg) {
                showToast(R.string.nfc_not_support);
            }
            return;
        }
        if (!mNfcAdapter.isEnabled()) {
            if (showMsg) {
                showToast(R.string.nfc_not_enabled);
            }
            return;
        }
        if (showMsg) {
            showToast(R.string.nfc_please_near);
        }
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);//创建PendingIntent对象,当检测到一个Tag标签就会执行此Intent
        tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    }

    public void startNfc(boolean showMsg) {
        //注意，该方法必须在页面resume后调用，不然会crash
        try {
            initNfc(showMsg);
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, new IntentFilter[]{tagDetected}, new String[][]{new String[]{NfcA.class.getName()}});//打开前台发布系统，使页面优于其它nfc处理.当检测到一个Tag标签就会执行mPendingItent
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, new IntentFilter[]{tagDetected}, new String[][]{new String[]{NfcA.class.getName()}});//打开前台发布系统，使页面优于其它nfc处理.当检测到一个Tag标签就会执行mPendingItent
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
            mNfcAdapter.disableForegroundDispatch(this);//关闭前台发布系统
        }
    }

    private void setLandscape() {
        // 全屏不透明Activity才能设置Orientation,否则在高版本Android会Crash,复现版本为8.0
        // 错误信息: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
        try {
            if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    protected void errorOnRetry() {
    }

    protected void emptyOnRetry() {
    }

    protected void noNetworkOnRetry() {
    }


    @Override
    public boolean isDestroy() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return isDestroyed();
        }
        return false;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                if (fragment != null) {
                    dispatchActivityResult(fragment, requestCode, resultCode, data);
                }
            }
        }
    }

    private void dispatchActivityResult(Fragment fragment, int requestCode, int resultCode, Intent data) {
        fragment.onActivityResult(requestCode, resultCode, data);
        List<Fragment> children = fragment.getChildFragmentManager().getFragments();
        if (children != null)
            for (Fragment child : children)
                if (child != null) {
                    dispatchActivityResult(child, requestCode, resultCode, data);
                }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Progress.dismissProgressDialog(this);
        FragmentManager fm = getSupportFragmentManager();
        while (fm.getBackStackEntryCount() > 0) {
            fm.popBackStackImmediate();
        }
    }

    @Override
    public Handler getUIHandler() {
        if (uiHandler == null) {
            uiHandler = new Handler(Looper.getMainLooper());
        }
        return uiHandler;
    }

    @Override
    public CustomProgressDialog getProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new CustomProgressDialog(this);
        }
        return progressDialog;
    }

    public ViewGroup getRootLayout() {
        return rootLayout;
    }

    private ViewGroup getAndClearContentLayout() {
        contentLayout.removeAllViewsInLayout();
        return contentLayout;
    }

    @Override
    public void setContentView(int layoutResID) {
        LayoutInflater.from(this).inflate(layoutResID, getAndClearContentLayout());
        onContentChanged();//因为我们重写了setContentView,因此要重新把这个回调执行
    }

    @Override
    public void setContentView(View view) {
        getAndClearContentLayout().addView(view);
        onContentChanged();//因为我们重写了setContentView,因此要重新把这个回调执行
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getAndClearContentLayout().addView(view, params);
        onContentChanged();//因为我们重写了setContentView,因此要重新把这个回调执行
    }

    protected void showProgressDialog(@StringRes int resId) {
        String content = getString(resId);
        showProgressDialog(content);
    }

    protected void showProgressDialog(final String content) {
        Progress.showProgressDialog(BaseActivity.this, content, 0, 0, 0, 0);
    }

    protected void showProgressDialogNoMsg() {
        showProgressDialog("");
    }

    protected void dismissProgress() {
        try {
            Progress.dismissProgressDialog(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void showToast(@StringRes int resId) {
        String content = getString(resId);
        showToast(content);
    }

    protected void showToast(String content) {
        BaseToast.showToast(this, content);
    }

    protected void showToastException(@StringRes int resId) {
        String content = getString(resId);
        showToastException(content);
    }

    protected void showToastException(String content) {
        BaseToast.toastException(this, content);
    }

    /**
     * 跳转页面
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(this, clz));
    }

    @Override
    public void onBackPressed() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null && !fragments.isEmpty()) {
            for (int i = fragments.size() - 1; i >= 0; i--) {
                Fragment child = fragments.get(i);
                if (child.getChildFragmentManager().popBackStackImmediate()) {
                    return;
                }
            }
        }
        if (getSupportFragmentManager().popBackStackImmediate()) {
            return;
        }
        super.onBackPressed();
    }

    protected boolean isNetAvailable() {
        if (!NetworkUtils.isConnected(this)) {
            showToast(R.string.net_error);
            return false;
        } else {
            return true;
        }
    }

    public class SimpleStateCallback<T> implements StateResource.OnHandleCallback<T> {

        @Override
        public void onLoading() {
            showProgressDialogNoMsg();
        }

        @Override
        public void onSuccess(T data) {

        }

        @Override
        public void onFailure(String message) {

        }

        @Override
        public void onCompleted() {
            dismissProgress();
        }
    }
}
